package study.cv.opencv.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import study.cv.opencv.support.utils.WinUtils;

import java.util.List;

@Slf4j
public class SptAns_Test {

    private String inputFile = "d:/image/spt_ans/AB.png";

    @Before
    public void init() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    @Test
    public void test() {
        tryGetAns(inputFile, 4);
    }

    public String tryGetAns(String inputFile, int size) {
        //读取原始图像
        Mat src = Imgcodecs.imread(inputFile);
        //
        int rows = src.rows();
        int cols = src.cols();

        //
        int width = cols / size;
        int height = rows;
        //
        for (int i = 0; i < size; i++) {
            //
            int x = (i) * width;
            int y = 0;
            Mat mat = cut(src, x, y, width, rows);
//            Core.bitwise_not(mat, mat);
//            Mat kernel = I mgproc.getStructuringElement(1, new Size(3, 3));
//            Point anchor = new Point(-1, -1);
//            Imgproc.erode(mat, mat, new Mat());
//            Imgproc.dilate(mat, mat, kernel);
//            Imgproc.erode(mat, mat, kernel, anchor, 1);


            WinUtils.imShow("截取", mat);

            //
            preDoing(mat);
            //
            List<MatOfPoint> contourLt = getContour(mat);
            log.info("轮廓数量= {}", contourLt.size());
            //
            identifyAns(i, contourLt.size());
//            Mat t = Utils.drawContoursAtRaw(mat, contourLt);
//            Windows.imShow("截取", t);
        }

        return null;
    }


    private Mat cut(Mat image, int x, int y, int width, int height) {
        // log.info("x= {}, y= {}, width={}, height= {}", x, y, width, height);
        //坐标
        Point p = new Point(x, y);
        //宽高
        Size s = new Size(width, height);
        //
        Rect rect = new Rect(p, s);
        Mat mat = image.submat(rect);
        return mat;
    }

    private void preDoing(Mat src) {
        //
        Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY);
        //
        Imgproc.threshold(src, src, 127, 255, Imgproc.THRESH_BINARY_INV);
    }

    private List<MatOfPoint> getContour(Mat src) {
        List<MatOfPoint> contourLt = Lists.newArrayList();
        Mat hierarchy = new Mat();
        Imgproc.findContours(src, contourLt, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
        return contourLt;
    }

    private char identifyAns(int seq, int size) {
        char ans = ' ';
        if (size == 1) {
            ans = (char) (seq + 65);
            log.info("seq={}, size= {} 答案: {}", seq, size, ans);
        }
        return ans;
    }
}
